from typing import List


class Solution:
    def ringGame(self, challenge: List[int]) -> int:
        # 预处理目标数组
        now_challenge = [[v, v] for v in challenge]

        now_bit = 1 << (max(challenge).bit_length())
        now_val = 0
        while now_bit > 1:
            # 当前填充值
            now_val += (now_bit >> 1)

            # 当前位
            now_bit >>= 1

            print("当前位:", now_bit, "当前填充值:", now_val)

            nxt_challenge = []
            less_val = 0
            for v, m in now_challenge:
                if not m & now_bit:
                    less_val |= m
                else:
                    if len(nxt_challenge) > 0:
                        nxt_challenge[-1][1] |= less_val
                    if less_val > 0:
                        nxt_challenge.append([now_val, now_val | less_val])
                    nxt_challenge.append([v, m | less_val])
                    less_val = 0
            nxt_challenge[-1][1] |= less_val
            print("处理结果:", nxt_challenge)

            # ----- 处理双向可合并的情况 -----
            clear1 = []
            for v2, m2 in nxt_challenge:
                if not clear1:
                    clear1.append([v2, m2])
                    continue

                v1, m1 = clear1[-1]

                if m1 >= v2 and m2 >= v1:
                    clear1[-1][0] = min(v1, v2)
                    clear1[-1][1] = max(m1, m2)
                else:
                    clear1.append([v2, m2])
            print("整理结果:", clear1)

            # ----- 处理已经得出结果的情况 -----
            if len(clear1) == 1:
                return clear1[0][0]

            now_challenge = clear1


if __name__ == "__main__":
    print(Solution().ringGame(challenge=[5, 4, 6, 2, 7]))  # 4
    print(Solution().ringGame(challenge=[12, 7, 11, 3, 9]))  # 8
    print(Solution().ringGame(challenge=[1, 1, 1]))  # 1

    # 自制用例
    print(Solution().ringGame(challenge=[15, 6, 15, 1]))  # 15
    print(Solution().ringGame(challenge=[5, 7, 11, 13, 14, 15]))  # 8
    print(Solution().ringGame(challenge=[15, 11, 13, 15]))  # 12
    print(Solution().ringGame(challenge=[15, 14, 15]))  # 15
    print(Solution().ringGame(challenge=[15, 10, 15]))  # 13
